<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="多线程," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="为避免ANR，我们需要把一些耗时的操作，放在一个子线程中。但更新UI只能在主线程中更新。所以Handler就出现了。由于Handler运行在主线程中(UI线程中)，它与子线程可以通信，把这些消息放入主线程队列中，配合主线程进行更新UI。">
<meta property="og:type" content="article">
<meta property="og:title" content="Handler">
<meta property="og:url" content="http://yoursite.com/2017/03/01/201703/Handler/index.html">
<meta property="og:site_name" content="HoneyGuide's Blog">
<meta property="og:description" content="为避免ANR，我们需要把一些耗时的操作，放在一个子线程中。但更新UI只能在主线程中更新。所以Handler就出现了。由于Handler运行在主线程中(UI线程中)，它与子线程可以通信，把这些消息放入主线程队列中，配合主线程进行更新UI。">
<meta property="og:image" content="http://yoursite.com/img/201703/handler1.png">
<meta property="og:image" content="http://yoursite.com/img/201703/handler2.png">
<meta property="og:updated_time" content="2017-03-01T02:58:55.303Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Handler">
<meta name="twitter:description" content="为避免ANR，我们需要把一些耗时的操作，放在一个子线程中。但更新UI只能在主线程中更新。所以Handler就出现了。由于Handler运行在主线程中(UI线程中)，它与子线程可以通信，把这些消息放入主线程队列中，配合主线程进行更新UI。">
<meta name="twitter:image" content="http://yoursite.com/img/201703/handler1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'R1W2VDDO1V',
      apiKey: '773854c4c250e5a5cf9cddd97ebcc167',
      indexName: 'Hexo_search',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/03/01/201703/Handler/"/>





  <title> Handler | HoneyGuide's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">﻿<div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">HoneyGuide's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay hungry & Stay young</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">

　　　　　　<!--增加的代码 start-->

          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/03/01/201703/Handler/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="HoneyGuide">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HoneyGuide's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Handler
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-01T00:00:00+08:00">
                2017-03-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>为避免ANR，我们需要把一些耗时的操作，放在一个子线程中。但更新UI只能在主线程中更新。所以Handler就出现了。由于Handler运行在主线程中(UI线程中)，它与子线程可以通信，把这些消息放入主线程队列中，配合主线程进行更新UI。<br><a id="more"></a></p>
<h3 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h3><p>主要接受子线程发送的数据， 并用此数据配合主线程更新UI。</p>
<h3 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h3><p>handler可以分发Message对象和Runnable对象到主线程中，每个Handler实例，都会绑定到创建他的线程中(一般是位于主线程)，它有两个作用：</p>
<ol>
<li>安排消息或Runnable在某个主线程中某个地方执行；</li>
<li>安排一个动作在不同的线程中执行。</li>
</ol>
<p>Handler可以通过这两个队列来分别：</p>
<ol>
<li>发送、接受、处理消息–消息队列；</li>
<li>启动、结束、休眠线程–Runnable队列；</li>
</ol>
<p><img src="/img/201703/handler1.png" alt="image"></p>
<p>Handler中分发消息的一些方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">post(Runnable)</div><div class="line">postAtTime(Runnable，long)</div><div class="line">postDelayed(Runnable long)</div><div class="line">sendEmptyMessage(int)</div><div class="line">sendMessage(Message)</div><div class="line">sendMessageAtTime(Message，long)</div><div class="line">sendMessageDelayed(Message，long)</div></pre></td></tr></table></figure></p>
<p>以上post类方法允许你排列一个Runnable对象到主线程队列中，<br>sendMessage类方法， 允许你安排一个带数据的Message对象到队列中，等待更新。</p>
<h3 id="Runnable队列"><a href="#Runnable队列" class="headerlink" title="Runnable队列"></a>Runnable队列</h3><h4 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h4><p>Android的线程异步处理机制：Handler对象维护一个线程队列，有新的Runnable送来（post()）的时候,把它放在队尾，而处理Runnable的时候，从队头取出Runnable执行。当向队列发送一个Runnable后，立即就返回，并不理会Runnable是否被执行，执行是否成功等。而具体的执行则是当排队排到该Runnable后系统拿来执行的。这就好比邮局的例子。寄信者将信写好后放入邮筒就回家了，他并不知道邮件何 时被邮局分发，何时寄到，对方怎样读取这些事。这样，就实现了Android的异步处理机制。</p>
<h4 id="操作"><a href="#操作" class="headerlink" title="操作"></a>操作</h4><p>向队列添加线程：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">handler.post(Runnable );//将Runnable直接添加入队列</div><div class="line">handler.postDelayed(Runnable, long)//延迟一定时间后，将Runnable添加入队列</div><div class="line">handler.postAtTime(Runnable,long)//定时将Runnable添加入队列</div></pre></td></tr></table></figure></p>
<p>终止线程：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">handler.removeCallbacks(thread);//将Runnable从Runnable队列中取出</div></pre></td></tr></table></figure></p>
<h3 id="消息队列"><a href="#消息队列" class="headerlink" title="消息队列"></a>消息队列</h3><h4 id="消息对象"><a href="#消息对象" class="headerlink" title="消息对象"></a>消息对象</h4><h5 id="Message对象"><a href="#Message对象" class="headerlink" title="Message对象"></a>Message对象</h5><p>Message对象携带数据，通常它用arg1,arg2来传递消息，当然它还可以有obj参数，可以携带Bundle数据。它的特点是系统性能消耗非常少。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Message msg=handler.obtainMessage();</div></pre></td></tr></table></figure></p>
<h5 id="Bundle对象"><a href="#Bundle对象" class="headerlink" title="Bundle对象"></a>Bundle对象</h5><p>Bundle是Android提供的类，可以把它看做是特殊的Map，即键值对的包。而它特殊在键和值都必须要是基本数据类型或是基本数据类型的数组（Map的键值要求都是对象），特别的，键要求都是String类型。用Message来携带Bundle数据：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">msg.setData(Bundle bundle);</div><div class="line">msg.getData();</div></pre></td></tr></table></figure></p>
<h4 id="原理-1"><a href="#原理-1" class="headerlink" title="原理"></a>原理</h4><p>Android的消息异步处理机制：Handler对象维护一个消息队列，有新的消息送来（sendMessage()）的时候，把它放在队尾，之后排队到处理该消息的时候，由主线程的Handler对象处理(handleMessage())。整个过程也是异步的，和Runnable队列的原理相同。</p>
<h4 id="操作-1"><a href="#操作-1" class="headerlink" title="操作"></a>操作</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">handler.sendMessage(Message); //向队列添加Runnable</div><div class="line">msg.sendToTarget();//将消息发送到消息队列</div><div class="line">handler.sendMessageDelayed(Message,long);// 延迟一定时间后，将消息发送到消息队列</div><div class="line">handler.sendMessageAtTime(Message,long)// 定时将消息发送到消息队列</div></pre></td></tr></table></figure>
<p>消息的具体处理过程，需要在new Handler对象时使用匿名内部类重写Handler的handleMessage(Message msg)方法：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">Handler handler=new Handler()&#123; </div><div class="line"> </div><div class="line">@Override </div><div class="line">public void handleMessage(Message msg) &#123; </div><div class="line">// TODO Auto-generated method stub </div><div class="line">……&#125; </div><div class="line">&#125;;</div></pre></td></tr></table></figure></p>
<h3 id="Handler实例"><a href="#Handler实例" class="headerlink" title="Handler实例"></a>Handler实例</h3><p>子类需要继承Hendler类，并重写handleMessage(Message msg) 方法，用于接受线程数据。<br>以下为一个实例，它实现的功能为：通过线程修改界面Button的内容<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div></pre></td><td class="code"><pre><div class="line">public class MyHandlerActivity extends Activity &#123; </div><div class="line">    Button button; </div><div class="line">    MyHandler myHandler; </div><div class="line"> </div><div class="line">    protected void onCreate(Bundle savedInstanceState) &#123; </div><div class="line">        super。onCreate(savedInstanceState); </div><div class="line">        setContentView(R。layout。handlertest); </div><div class="line"> </div><div class="line">        button = (Button) findViewById(R。id。button); </div><div class="line">        myHandler = new MyHandler(); </div><div class="line">        // 当创建一个新的Handler实例时， 它会绑定到当前线程和消息的队列中，开始分发数据 </div><div class="line">        // Handler有两个作用， (1) : 定时执行Message和Runnalbe 对象 </div><div class="line">        // (2): 让一个动作，在不同的线程中执行。 </div><div class="line"> </div><div class="line">        // 它安排消息，用以下方法 </div><div class="line">        // post(Runnable) </div><div class="line">        // postAtTime(Runnable，long) </div><div class="line">        // postDelayed(Runnable，long) </div><div class="line">        // sendEmptyMessage(int) </div><div class="line">        // sendMessage(Message); </div><div class="line">        // sendMessageAtTime(Message，long) </div><div class="line">        // sendMessageDelayed(Message，long) </div><div class="line">      </div><div class="line">        // 以上方法以 post开头的允许你处理Runnable对象 </div><div class="line">        //sendMessage()允许你处理Message对象(Message里可以包含数据，) </div><div class="line"> </div><div class="line">        MyThread m = new MyThread(); </div><div class="line">        new Thread(m)。start(); </div><div class="line">    &#125; </div><div class="line"> </div><div class="line">    /** </div><div class="line">    * 接受消息，处理消息 ，此Handler会与当前主线程一块运行 </div><div class="line">    * */ </div><div class="line"> </div><div class="line">    class MyHandler extends Handler &#123; </div><div class="line">        public MyHandler() &#123; </div><div class="line">        &#125; </div><div class="line"> </div><div class="line">        public MyHandler(Looper L) &#123; </div><div class="line">            super(L); </div><div class="line">        &#125; </div><div class="line"> </div><div class="line">        // 子类必须重写此方法，接受数据 </div><div class="line">        @Override </div><div class="line">        public void handleMessage(Message msg) &#123; </div><div class="line">            // TODO Auto-generated method stub </div><div class="line">            Log。d(&quot;MyHandler&quot;， &quot;handleMessage。。。。。。&quot;); </div><div class="line">            super。handleMessage(msg); </div><div class="line">            // 此处可以更新UI </div><div class="line">            Bundle b = msg。getData(); </div><div class="line">            String color = b。getString(&quot;color&quot;); </div><div class="line">            MyHandlerActivity。this。button。append(color); </div><div class="line"> </div><div class="line">        &#125; </div><div class="line">    &#125; </div><div class="line"> </div><div class="line">    class MyThread implements Runnable &#123; </div><div class="line">        public void run() &#123; </div><div class="line"> </div><div class="line">            try &#123; </div><div class="line">                Thread。sleep(10000); </div><div class="line">            &#125; catch (InterruptedException e) &#123; </div><div class="line">                // TODO Auto-generated catch block </div><div class="line">                e。printStackTrace(); </div><div class="line">            &#125; </div><div class="line"> </div><div class="line">            Log。d(&quot;thread。。。。。。。&quot;， &quot;mThread。。。。。。。。&quot;); </div><div class="line">            Message msg = new Message(); </div><div class="line">            Bundle b = new Bundle();// 存放数据 </div><div class="line">            b。putString(&quot;color&quot;， &quot;我的&quot;); </div><div class="line">            msg。setData(b); </div><div class="line"> </div><div class="line">            MyHandlerActivity。this。myHandler。sendMessage(msg); // 向Handler发送消息，更新UI </div><div class="line"> </div><div class="line">        &#125; </div><div class="line">    &#125; </div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="Looper"><a href="#Looper" class="headerlink" title="Looper"></a>Looper</h3><p>Looper类用来为线程开启一个消息循环，作用是可以循环的从消息队列读取消息，所以Looper实际上就是消息队列+消息循环的封装。每个线程只能对应一个Looper，除主线程外，Android中的线程默认是没有开启Looper的。</p>
<p>通过Handler与Looper交互，Handler可以看做是Looper的接口，用来向指定的Looper发送消息以及定义处理方法。默认情况下Handler会与其所在线程的Looper绑定：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">Handler handler=new Handler();//等价于</div><div class="line">Handler handler=new Handler(Looper.myLooper());</div></pre></td></tr></table></figure></p>
<h4 id="方法"><a href="#方法" class="headerlink" title="方法"></a>方法</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">Looper.prepare();//启用Looper</div><div class="line">Looper.loop(); //让Looper开始工作，从消息队列里取消息，处理消息。</div></pre></td></tr></table></figure>
<p>注意：写在Looper.loop()之后的代码不会被执行，这个函数内部应该是一个循环，当调用mHandler.getLooper().quit()后，loop才会中止，其后的代码才能得以运行。</p>
<h4 id="作用"><a href="#作用" class="headerlink" title="作用"></a>作用</h4><ul>
<li>与当前线程绑定，保证一个线程只会有一个Looper实例，同时一个Looper实例也只有一个MessageQueue。</li>
<li>loop()方法，不断从MessageQueue中去取消息，交给消息的target属性的dispatchMessage去处理。</li>
</ul>
<p>异步消息处理线程已经有了消息队列（MessageQueue），也有了在无限循环体中取出消息的对象，现在缺的就是发送消息的对象了，于是乎：Handler登场了。</p>
<h4 id="Handler异步机制的实现"><a href="#Handler异步机制的实现" class="headerlink" title="Handler异步机制的实现"></a>Handler异步机制的实现</h4><p>Handler是通过HandlerThread使得子线程与主线程分属不同线程的。实际上，HandlerThread 是一个特殊的线程，它是一个封装好Looper的线程。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"> //创建一个名叫handler_hread的HandlerThread 对象 </div><div class="line">HandlerThread handlerThread=new HandlerThread(&quot;handler_hread&quot;); </div><div class="line"> </div><div class="line">//开启handlerThread，在使用handlerThread.getLooper()之前必须先调用start方法，否则取出的是空 </div><div class="line">handlerThread.start(); </div><div class="line"> </div><div class="line">//将handler绑定在handlerThread的Looper上，即这个handler是运行在handlerThread线程中的 </div><div class="line">myHandler handler=new myHandler(handlerThread.getLooper()); </div><div class="line"> </div><div class="line">class myHandler extends Handler&#123; </div><div class="line">    public myHandler()&#123;&#125; </div><div class="line">    public myHandler(Looper looper)&#123; </div><div class="line">        super(looper); </div><div class="line">    &#125; </div><div class="line">    @Override </div><div class="line">    public void handleMessage(Message msg) &#123; </div><div class="line">        // TODO Auto-generated method stub </div><div class="line">        System.out.println(&quot;Activity Thread:&quot;+Thread.currentThread().getId()); </div><div class="line">    &#125; </div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>这样，就实现了handler的异步处理机制，在调用handler.post()方法，通过打印线程ID可以得知，子线程与主线程是分属不同线程的。</p>
<ul>
<li>首先Looper.prepare()在本线程中保存一个Looper实例，然后该实例中保存一个MessageQueue对象；因为Looper.prepare()在一个线程中只能调用一次，所以MessageQueue在一个线程中只会存在一个。</li>
<li>Looper.loop()会让当前线程进入一个无限循环，不端从MessageQueue的实例中读取消息，然后回调msg.target.dispatchMessage(msg)方法。</li>
<li>Handler的构造方法，会首先得到当前线程中保存的Looper实例，进而与Looper实例中的MessageQueue想关联。</li>
<li>Handler的sendMessage方法，会给msg的target赋值为handler自身，然后加入MessageQueue中。</li>
<li>在构造Handler实例时，我们会重写handleMessage方法，也就是msg.target.dispatchMessage(msg)最终调用的方法。</li>
</ul>
<p>在Activity中，我们并没有显示的调用Looper.prepare()和Looper.loop()方法，为啥Handler可以成功创建呢，这是因为<em>在Activity的启动代码中，已经在当前UI线程调用了Looper.prepare()和Looper.loop()方法</em>。</p>
<p><img src="/img/201703/handler2.png" alt="image"></p>
<h3 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h3><p><a href="http://mobile.51cto.com/aprogram-442833.htm" target="_blank" rel="external">http://mobile.51cto.com/aprogram-442833.htm</a><br><a href="http://mobile.51cto.com/abased-375243.htm" target="_blank" rel="external">http://mobile.51cto.com/abased-375243.htm</a><br><a href="http://blog.csdn.net/lmj623565791/article/details/38377229/" target="_blank" rel="external">http://blog.csdn.net/lmj623565791/article/details/38377229/</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/多线程/" rel="tag"># 多线程</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/02/28/201702/AsyncTask介绍/" rel="next" title="AsyncTask介绍">
                <i class="fa fa-chevron-left"></i> AsyncTask介绍
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/01/201703/PendingIntent/" rel="prev" title="PendingIntent">
                PendingIntent <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="HoneyGuide" />
          <p class="site-author-name" itemprop="name">HoneyGuide</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">34</span>
                <span class="site-state-item-name">标签</span>
              
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#定义"><span class="nav-number">1.</span> <span class="nav-text">定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#特点"><span class="nav-number">2.</span> <span class="nav-text">特点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Runnable队列"><span class="nav-number">3.</span> <span class="nav-text">Runnable队列</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#原理"><span class="nav-number">3.1.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#操作"><span class="nav-number">3.2.</span> <span class="nav-text">操作</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#消息队列"><span class="nav-number">4.</span> <span class="nav-text">消息队列</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#消息对象"><span class="nav-number">4.1.</span> <span class="nav-text">消息对象</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#Message对象"><span class="nav-number">4.1.1.</span> <span class="nav-text">Message对象</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Bundle对象"><span class="nav-number">4.1.2.</span> <span class="nav-text">Bundle对象</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#原理-1"><span class="nav-number">4.2.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#操作-1"><span class="nav-number">4.3.</span> <span class="nav-text">操作</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Handler实例"><span class="nav-number">5.</span> <span class="nav-text">Handler实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Looper"><span class="nav-number">6.</span> <span class="nav-text">Looper</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#方法"><span class="nav-number">6.1.</span> <span class="nav-text">方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#作用"><span class="nav-number">6.2.</span> <span class="nav-text">作用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Handler异步机制的实现"><span class="nav-number">6.3.</span> <span class="nav-text">Handler异步机制的实现</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考"><span class="nav-number">7.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HoneyGuide</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  



  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="local-search-pop-overlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


  

</body>
</html>
